package com.apes.fn.fico.expense;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.fileserver.File;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.finance.model.IncomeType;
import com.apes.scm.masterdata.frame.model.Channel;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ExpenseItem.CONST_TABLE_NAME)
public class ExpenseItem extends BaseModel {

    public static final String CONST_TABLE_NAME = "fn_expense_item";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "费用单明细编码")
    @Comment("编码")
    private String id;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "expense_id", referencedColumnName = "id")
    @Comment("费用单号")
    private Expense expense; /*收入主表*/

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tenant_id", referencedColumnName = "id")
    @Comment("公司编码(商户)")
    private PartyRole company;

    @Comment("结算政策(来源单据号码)")
    @Column(name = "settle_policy", length = 4000)
    private String settlePolicy;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "expense_type_id", referencedColumnName = "id")
    @Comment("费用类型")
    private IncomeType expenseType;


    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("费用金额")
    private double amount = 0;

    @Column(name = "withholding_amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("预扣收金额")
    private double withholdingAmount = 0;


    @Column(name = "amount_deducted", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("已扣收金额")
    private double amountDeducted = 0;

    public void setAmountDeducted(double amountDeducted) {
        this.amountDeducted = amountDeducted;
        if (Math.abs(this.amountDeducted) > Math.abs(this.amount)) {
            throw new RuntimeException("已扣收金额超出费用金额！");
        }
    }

    @Comment("费用周期起")
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "period_start")
    private Date periodStart;


    @Comment("费用周期止")
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "period_end")
    private Date periodEnd;


    @Comment("计算日期")
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "calculate_date")
    private Date calculateDate;


    @Column(name = "arrival_date")
    @Comment("到账日期")
    private Date arrivalDate;

    @Column(name = "remark", length = 250)
    @Comment("备注")
    private String remark;

    @File
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "annex", columnDefinition = "CLOB")
    private String annex;


    @Comment("渠道")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "channel_id", referencedColumnName = "id")
    private Channel channel;

    @Name
    @Column(name = "car_license", length = 64)
    @Comment("车牌号码")
    private String carLicense;

    @Comment("源单据")
    @Column(name = "origin", length = 30)
    private String origin;

    @Column(name = "source", length = 100)
    @Comment("源单号")
    private String source;

    @Transient
    private IncomeType incomeType;

    public IncomeType getIncomeType() {
        return this.expenseType;
    }

    public IncomeType getExpenseType() {
        return this.incomeType == null ? this.expenseType : this.incomeType;
    }

    @OneToMany(mappedBy = "expenseItem", cascade = CascadeType.ALL)
    private List<ExpenseItemDetails> expenseItemDetailsList = new ArrayList();

    public List<ExpenseItemDetails> getExpenseItemDetailsList() {
        if (expenseItemDetailsList == null || expenseItemDetailsList.isEmpty()) return new ArrayList<>();
        for (ExpenseItemDetails expenseItemDetails : expenseItemDetailsList) {
            expenseItemDetails.setExpenseItem(this);
        }
        return expenseItemDetailsList;
    }

    @Transient
    private Enumeration inComeCategory;

    public Enumeration getInComeCategory() {
        if (Objects.isNull(this.expenseType)) return null;
        return this.expenseType.getInComeCategory();
    }

}
